import type {FormProps} from 'antd';
import {Form as AntdForm} from 'antd';
import {CommonComponentProps} from "../../../../components/editor/interface.ts";
import {useDrag} from "react-dnd";
import {useMateRailDrop} from "../../../hooks/useMaterialDrop.ts";
import React, {useEffect, useMemo, useRef} from "react";
import {FormDndAccept} from "../../DnDAccept.tsx";

type FieldType = {
    username?: string;
    password?: string;
    remember?: string;
};

const onFinish: FormProps<FieldType>['onFinish'] = (values) => {
    console.log('Success:', values);
};

const onFinishFailed: FormProps<FieldType>['onFinishFailed'] = (errorInfo) => {
    console.log('Failed:', errorInfo);
};
const FormDev = (props: CommonComponentProps) => {
    const {id, styles, name, children} = props
    const [form] = AntdForm.useForm();
    const divRef = useRef<HTMLDivElement>(null);

    const {
        canDrop,
        drop
    } = useMateRailDrop([...FormDndAccept], id)
    const nameId = name === "Form" ? name + "_" + id.toString().slice(id.toString().length - 5, id.toString().length) : name
    // 拖拽设置
    const [_, drag] = useDrag({
        type: "Form",
        item: {
            id,
            type: name,
            dragType: "move"
        }
    })

    useEffect(() => {
        drop(divRef);
        drag(divRef);
    }, []);

    const formItems = useMemo(() => {
        return React.Children.map(children, (item: any) => {
            if (item.name === "Flex" || item.name === "Grid") return;
            return {
                label: item.props?.label,
                name: item.props?.name,
                type: item.props?.type,
                id: item.props?.id,
                dev: item
            }
        })
    }, [children])


    return (
        <div data-component-id={id} style={styles} ref={divRef}
             className={`w-[100%] p-[20px] min-h-[100px] ${canDrop ? 'border-[2px] border-[blue]' : 'border-[1px] border-[#000]'}`}>
            <AntdForm
                name={nameId}
                labelCol={{span: 3}}
                wrapperCol={{span: 17}}
                layout={props.layout}
                // style={{maxWidth: 600}}
                onFinish={onFinish}
                onFinishFailed={onFinishFailed}
                form={form}
                autoComplete="off"
            >
                {
                    formItems && formItems.map((item: any) => {
                        return <div key={item.id}>
                            {item.dev}
                        </div>
                    })
                }
            </AntdForm>
        </div>
    );
};

export default FormDev;